package com.example.okhttp;

import static android.widget.Toast.LENGTH_SHORT;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.okhttp.Get.TestGet;
import com.example.okhttp.databinding.ActivityMainBinding;

import java.io.IOException;

import okhttp3.OkHttpClient;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ActivityMainBinding binding;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //获取viewBinding对象
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        binding.btnExcute.setOnClickListener(this);
        binding.btnEnqueue.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_excute:
                //同步执行需要在子线程中进行
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            String str = TestGet.getInstance().testExecuteGet("https://lf2022.cn/");
                            //在主线程进行更新
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    binding.textView.setText(str);
                                }
                            });
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }).start();
                break;
            case R.id.btn_enqueue:
                TestGet.getInstance().testEnqueueGet("https://lf2022.cn/", new MyCallBack() {
                    @Override
                    public void onSuccess(String str) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                binding.textView.setText(str);
                            }
                        });
                    }

                    @Override
                    public void onError(Exception e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("guaimiao" , "失败");
                            }
                        });
                    }
                });
                break;
        }

    }
}